package com.woyao;

import android.app.Application;
import android.app.Dialog;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.woyao.core.model.BaseResponse;
import com.woyao.core.model.DemandSummary;
import com.woyao.core.model.GetMyDemandResponse;
import com.woyao.core.model.ProfileResponse;
import com.woyao.core.model.User;
import com.woyao.core.service.AccountService;
import com.woyao.core.util.Common;
import com.woyao.core.util.ServiceFactory;
import com.woyao.core.util.StringUtil;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;
import retrofit2.Call;

import static android.content.Context.MODE_PRIVATE;
import static com.woyao.R.id.avatar;
import static com.woyao.WoyaoooApplication.userId;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link PersonFragment.OnPersonFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link PersonFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class PersonFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    TextView username;   //  current user name
    TextView userLocation;
    TextView userTitle;
    TextView userVerify;
    Button addUpdateBtn;
    Button customServiceBtn;
    User user;
    private CircleImageView user_avatar;

    TextView updates_num ;
    TextView followers_num ;
    TextView marked_num ;
    TextView history_num ;
    TextView performanceTxt ;

//    private User user;
    public UserViewModel uvm;

    LinearLayout theview;
    Toolbar toolbar;

    private Integer MYACCOUNT_CODE = 100;
    private Integer ADD_DEMAND_CODE = 2000;
    private Integer ADD_UPDATE_CODE = 3000;
    private Integer MYVERIFY_CODE = 300;
    private Integer MYMONEY_CODE = 400;
    private Integer MYDEMAND_CODE = 500;
    private Integer MYREGISTER_CODE = 600;

    private OnPersonFragmentInteractionListener mListener;

    public PersonFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment PersonFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static PersonFragment newInstance(String param1, String param2) {
        PersonFragment fragment = new PersonFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public void onResume() {
        loadUserBasic();

        super.onResume();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        theview = (LinearLayout) inflater.inflate(R.layout.fragment_person, container, false);
        toolbar = (Toolbar) theview.findViewById(R.id.toolbar);

        performanceTxt =  (TextView) theview.findViewById(R.id.user_performance);

        customServiceBtn =  (Button) theview.findViewById(R.id.person_custom_service);

        customServiceBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_DIAL);
                Uri data = Uri.parse("tel:" + user.getCustomer_service());
                intent.setData(data);
                startActivity(intent);
            }
        });

        Button procotolBtn = (Button) theview.findViewById(R.id.protocol);
        procotolBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(getContext(), WebviewActivity.class);
                intent.putExtra("title", "用户协议");
                intent.putExtra("link", "https://www.woyaooo.com/protocol.html");
                startActivity(intent);
            }
        });

        Button privacyBtn = (Button) theview.findViewById(R.id.privacy);
        privacyBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(getContext(), WebviewActivity.class);
                intent.putExtra("title", "用户协议/隐私政策");
                intent.putExtra("link", "https://www.woyaooo.com/privacy.html");
                startActivity(intent);
            }
        });

        addUpdateBtn  = (Button) theview.findViewById(R.id.add_update);

        addUpdateBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!WoyaoooApplication.hasLogin){
                    Intent intent = new Intent();
                    intent.setClass(getContext(), RegisterActivity.class);
                    startActivityForResult(intent,MYREGISTER_CODE);
                    return;
                }
                AddDemand();
//                publishUpdate();


            }
        });

        updates_num = (TextView) theview.findViewById(R.id.person_updates_num);
        followers_num = (TextView) theview.findViewById(R.id.person_followers_num);
        marked_num = (TextView) theview.findViewById(R.id.person_marked_num);
        history_num = (TextView) theview.findViewById(R.id.person_history_num);

        Button updatesBtn = (Button) theview.findViewById(R.id.person_updates);
        Button followersBtn = (Button) theview.findViewById(R.id.person_followers);
        Button markedBtn = (Button) theview.findViewById(R.id.person_marked);
        Button historyBtn = (Button) theview.findViewById(R.id.person_history);

        historyBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!WoyaoooApplication.hasLogin){
                    Intent intent = new Intent();
                    intent.setClass(getContext(), RegisterActivity.class);
                    startActivityForResult(intent,MYREGISTER_CODE);
                    return;
                }


                Intent intent = new Intent();
                intent.putExtra("content","history");
                intent.setClass(getContext(), MyMarkActivity.class);
                startActivity(intent);
            }
        });

        markedBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!WoyaoooApplication.hasLogin){
                    Intent intent = new Intent();
                    intent.setClass(getContext(), RegisterActivity.class);
                    startActivityForResult(intent,MYREGISTER_CODE);
                    return;
                }


                Intent intent = new Intent();
                intent.putExtra("content","iapply");
                intent.setClass(getContext(), MyMarkActivity.class);
                startActivity(intent);
            }
        });

        updatesBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!WoyaoooApplication.hasLogin){
                    Intent intent = new Intent();
                    intent.setClass(getContext(), RegisterActivity.class);
                    startActivityForResult(intent,MYREGISTER_CODE);
                    return;
                }


                Intent intent = new Intent();
                intent.setClass(getContext(), MyUpdatesActivity.class);
                startActivity(intent);
            }
        });

        followersBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!WoyaoooApplication.hasLogin){
                    Intent intent = new Intent();
                    intent.setClass(getContext(), RegisterActivity.class);
                    startActivityForResult(intent,MYREGISTER_CODE);
                    return;
                }
                Intent intent = new Intent();
                intent.putExtra("content","applyme");
                intent.setClass(getContext(), MyMarkActivity.class);
                startActivity(intent);

            }
        });

//        talksBtn.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                mListener.onSwitchTab( 4,2);
//
//            }
//        });
//
//        agreementsBtn.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                mListener.onSwitchTab( 4,3);
//
//            }
//        });

        user_avatar = (CircleImageView) theview.findViewById(avatar);
        username = (TextView) theview.findViewById(R.id.usernameText);

        if ( WoyaoooApplication.displayname.equals("")) {
            username.setText("[填写个人资料]");
        }else{
            username.setText(WoyaoooApplication.displayname);
        }

        userLocation = (TextView)  theview.findViewById(R.id.userLocationText);
        userLocation.setText(WoyaoooApplication.location);

        userTitle = (TextView)  theview.findViewById(R.id.userTitleText);
        userTitle.setText(WoyaoooApplication.title);

        userVerify = (TextView)  theview.findViewById(R.id.userVerifyText);


        LinearLayout edit_personBtn = (LinearLayout) theview.findViewById(R.id.personal_info);

        edit_personBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                editUser();
            }
        });




        Button myverify = (Button) theview.findViewById(R.id.person_myverify);

        myverify.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!WoyaoooApplication.hasLogin){
                    Intent intent = new Intent();
                    intent.setClass(getContext(), RegisterActivity.class);
                    startActivityForResult(intent,MYREGISTER_CODE);
                    return;
                }
                Intent intent = new Intent();
                intent.setClass(getContext(), VerifyActivity.class);
                startActivityForResult(intent, MYVERIFY_CODE);
            }
        });

        ImageView mypreferImage = (ImageView) theview.findViewById(R.id.person_myprefer_image);
        Button myprefer = (Button) theview.findViewById(R.id.person_myprefer);

        mypreferImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(getContext(), PreferActivity.class);
                startActivity(intent);
            }
        });
        myprefer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!WoyaoooApplication.hasLogin){
                    Intent intent = new Intent();
                    intent.setClass(getContext(), RegisterActivity.class);
                    startActivityForResult(intent,MYREGISTER_CODE);
                    return;
                }
                Intent intent = new Intent();
                intent.setClass(getContext(), PreferActivity.class);
                startActivity(intent);
            }
        });

        Button mymark = (Button) theview.findViewById(R.id.person_mymark);

        mymark.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!WoyaoooApplication.hasLogin){
                    Intent intent = new Intent();
                    intent.setClass(getContext(), RegisterActivity.class);
                    startActivityForResult(intent,MYREGISTER_CODE);
                    return;
                }
                Intent intent = new Intent();
                intent.putExtra("content","mark");
                intent.setClass(getContext(), MyMarkActivity.class);

                startActivity(intent);
            }
        });

        Button myorgs = (Button) theview.findViewById(R.id.person_myorg);

        myorgs.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!WoyaoooApplication.hasLogin){
                    Intent intent = new Intent();
                    intent.setClass(getContext(), RegisterActivity.class);
                    startActivityForResult(intent,MYREGISTER_CODE);
                    return;
                }
                Intent intent = new Intent();
                intent.putExtra("content","mark");
                intent.setClass(getContext(), MyMemberActivity.class);

                startActivity(intent);
            }
        });

        Button mydemand = (Button) theview.findViewById(R.id.person_mydemand);

        mydemand.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!WoyaoooApplication.hasLogin){
                    Intent intent = new Intent();
                    intent.setClass(getContext(), RegisterActivity.class);
                    startActivityForResult(intent,MYREGISTER_CODE);
                    return;
                }
                Intent intent = new Intent();
                intent.setClass(getContext(), MyDemandActivity.class);

                startActivityForResult(intent,MYDEMAND_CODE);
            }
        });

        Button mymoney = (Button) theview.findViewById(R.id.person_mymoney);

        mymoney.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!WoyaoooApplication.hasLogin){
                    Intent intent = new Intent();
                    intent.setClass(getContext(), RegisterActivity.class);
                    startActivityForResult(intent,MYREGISTER_CODE);
                    return;
                }
                Intent intent = new Intent();
                intent.putExtra("money", 100.0);
                intent.setClass(getContext(), MoneyActivity.class);

                startActivityForResult(intent,MYMONEY_CODE);
            }
        });

        Button friendsBtn = (Button) theview.findViewById(R.id.person_friends);

        friendsBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!WoyaoooApplication.hasLogin){
                    Intent intent = new Intent();
                    intent.setClass(getContext(), RegisterActivity.class);
                    startActivityForResult(intent,MYREGISTER_CODE);
                    return;
                }
                Intent intent = new Intent();
                intent.setClass(getContext(), ContactsActivity.class);
                startActivity(intent);
//                Intent intent = new Intent();
//                intent.setClass(getContext(), SearchActivity.class);
//                intent.putExtra("keyword", "friends");
//                intent.putExtra("info", "chance");
//                startActivity(intent);
            }
        });

        Button myContactFriends = (Button) theview.findViewById(R.id.person_invite);

        myContactFriends.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!WoyaoooApplication.hasLogin){
                    Intent intent = new Intent();
                    intent.setClass(getContext(), RegisterActivity.class);
                    startActivityForResult(intent,MYREGISTER_CODE);
                    return;
                }
                Intent intent = new Intent();
                intent.setClass(getContext(), InviteActivity.class);

                startActivity(intent);
            }
        });

        Button myWeixinFriends = (Button) theview.findViewById(R.id.person_weixin);

        myWeixinFriends.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    String title = "我要合作网";
                    String description = "抓住合作机会";

                    Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);

                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                    int options = 90;
                    while (baos.toByteArray().length / 1024 > 32) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
                        baos.reset(); // 重置baos即清空baos
                        bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
                        options -= 10;// 每次都减少10
                    }
                    Bitmap photo_bmp = BitmapFactory.decodeByteArray(baos.toByteArray(), 0, baos.toByteArray().length);

//                    Common.shareWeb(getContext(), "wxae7ea097fe874f2c", "https://woyaooo.com?rid=" + userId, title, description, photo_bmp);
                }catch (Exception e){
                    Common.alert(getContext(),e.getMessage());

                };

            }
        });

        Button myhelp = (Button) theview.findViewById(R.id.person_myhelp);

        myhelp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(getContext(), WebviewActivity.class);
                intent.putExtra("title", "用户帮助");
                intent.putExtra("link", "https://www.woyaooo.com/charge.html?from=app");
                startActivity(intent);
            }
        });

        Button myquit = (Button) theview.findViewById(R.id.person_quit);

        myquit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                if (!WoyaoooApplication.hasLogin){
//                    Intent intent = new Intent();
//                    intent.setClass(getContext(), RegisterActivity.class);
//                    startActivityForResult(intent,MYREGISTER_CODE);
//                    return;
//                }

                SharedPreferences preferences =  getContext().getSharedPreferences("login", 0);
                SharedPreferences.Editor editor = preferences.edit();
                editor.putBoolean("logged", false);
                editor.putBoolean("agreed", false);
                editor.commit();
//                editor.clear();
                getActivity().finish();

//                Intent intent = new Intent(getContext(), RegisterActivity.class);
////                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                startActivityForResult(intent,MYREGISTER_CODE);
            }
        });

        Button myCancel = (Button) theview.findViewById(R.id.person_cancel);

        myCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!WoyaoooApplication.hasLogin){
                    Intent intent = new Intent();
                    intent.setClass(getContext(), RegisterActivity.class);
                    startActivityForResult(intent,MYREGISTER_CODE);
                    return ;
                }

                Dialog alertDialog = new AlertDialog.Builder(getContext()).
                        setTitle("警告").
                        setMessage("注销账号后，将不可恢复，注销吗？").
                        setIcon(R.drawable.ic_launcher).
                        setPositiveButton("确定", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                               cancelUser();
                            }
                        }).
                        setNegativeButton("取消", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        }).
                        create();
                alertDialog.show();


            }
        });

        uvm = ViewModelProviders.of(getActivity()).get(UserViewModel.class);
        displayProfile();
        // Inflate the layout for this fragment
        return theview;
    }

    private void publishUpdate( ){


        AsyncTask<Void, Void, GetMyDemandResponse> task =new AsyncTask<Void, Void, GetMyDemandResponse>() {
            @Override
            protected GetMyDemandResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<GetMyDemandResponse> responseCall = svc.getMyDemand(WoyaoooApplication.userId, "false");
                try {
                    GetMyDemandResponse response = responseCall.execute().body();
                    return response;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
            @Override
            protected void onPostExecute(final GetMyDemandResponse response) {

                final List<DemandSummary> demands = response.getContent();

                if (demands.size() ==0 ){
                    new AlertDialog.Builder(getContext())
                            .setTitle("信息")
                            .setMessage("请说明业务后，再发布动态。")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    AddDemand();
                                }
                            }).create().show();
                    return;
                }else{
                    Intent intent = new Intent();
                    intent.putExtra("id",0);
                    intent.putExtra("category","other");
                    intent.setClass(getContext(), MoveActivity.class);

                    startActivityForResult(intent, ADD_UPDATE_CODE);
                }

            }
            @Override
            protected void onCancelled() {

            }
        };
        task.execute((Void)null);

    }

    private Integer addUpdateChoice= 0;

    public  void AddDemand(){
        if (!WoyaoooApplication.hasLogin){
            Intent intent = new Intent();
            intent.setClass(getContext(), RegisterActivity.class);
            startActivityForResult(intent,MYREGISTER_CODE);
            return;
        }


        Intent intent = new Intent();
        intent.putExtra("from", "chance"  );
        intent.putExtra("is_new", true);
        intent.setClass(getContext(), DemandNewActivity.class);
        startActivityForResult(intent, ADD_DEMAND_CODE);
    }
    private void loadUserBasic(){
        Application application = getActivity().getApplication();
        SharedPreferences shared = application.getSharedPreferences("login", MODE_PRIVATE);

        try {
            WoyaoooApplication.hasLogin = shared.getBoolean("logged", false);
            WoyaoooApplication.userId = shared.getInt("userId", 0);
            WoyaoooApplication.displayname = shared.getString("displayname", "");;
            WoyaoooApplication.location = shared.getString("location", "");
            WoyaoooApplication.title = shared.getString("title", "");
            WoyaoooApplication.snailview = shared.getString("snailview", "");
            WoyaoooApplication.demand_id = shared.getInt("demand_id", 0);
            WoyaoooApplication.member_id = shared.getInt("member_id", 0);
            WoyaoooApplication.message_num = shared.getInt("message_num", 0);

        }catch (Exception e){

        }

        displayProfile();

    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onPersonFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnPersonFragmentInteractionListener) {
            mListener = (OnPersonFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnPersonFragmentInteractionListener {
        // TODO: Update argument type and name
        void onPersonFragmentInteraction(Uri uri);
        void onSwitchTab( Integer last_index, Integer new_index);
        void onMessage( Integer messageNum, String info);
    }

    private void editUser()
    {
        if (!WoyaoooApplication.hasLogin){
            Intent intent = new Intent();
            intent.setClass(getContext(), RegisterActivity.class);
            startActivityForResult(intent,MYREGISTER_CODE);
            return;
        }
        Intent intent = new Intent();
        intent.setClass(getContext(), AccountActivity.class);
        startActivityForResult(intent, MYACCOUNT_CODE);
    }
    public void loadProfile() {

        final String version = Common.getCurrentVersion(getContext());

        AsyncTask<Void, Void, ProfileResponse> loadTask =
                new AsyncTask<Void, Void, ProfileResponse>() {
                    @Override
                    protected ProfileResponse doInBackground(Void... params) {
                        AccountService svc = ServiceFactory.get(AccountService.class);
                        Call<ProfileResponse> responseCall = svc.getProfile(userId, "android",version);
                        try {
                            ProfileResponse response = responseCall.execute().body();
                            return response;
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(final ProfileResponse response) {
                        if (response != null && response.isSuccess()) {
                            User user = response.getContent();
                            uvm.initUser( user);

                            Application application = getActivity().getApplication();
                            SharedPreferences shared = application.getSharedPreferences("login", MODE_PRIVATE);
                            SharedPreferences.Editor editor = shared.edit();
                            editor.putInt("demand_id", user.getDemand_id());
                            editor.putString("displayname", user.getDisplayname());
                            editor.putString("snailview", user.getSnailview());
                            editor.putString("location", user.getLocation());
                            editor.putString("title", user.getTitle());
                            editor.putString("business", user.getBusiness());
                            editor.putString("business_name", user.getBusiness_name());
                            editor.putInt("member_id", user.getMember_id());
                            editor.putString("mobile", user.getMobile());
                            editor.putString("key", user.getKey());
                            editor.commit();
                            WoyaoooApplication.key = user.getKey();
                            WoyaoooApplication.snailview = user.getSnailview();
                            WoyaoooApplication.displayname = user.getDisplayname();
                            WoyaoooApplication.location = user.getLocation();
                            WoyaoooApplication.title = user.getTitle();
                            WoyaoooApplication.member_id = user.getMember_id();
                            WoyaoooApplication.demand_id = user.getDemand_id();


                            mListener.onMessage(user.getChance_num(), "chance" );
                            mListener.onMessage(user.getMessage_num(), "talk" );
                            mListener.onMessage(user.getCooperate_num(), "cooperate" );
                            mListener.onMessage(user.getPerson_num(), "person" );
                            mListener.onMessage(user.getInterest_num(), "interest" );

                            displayProfile();

                        }
                    }
                };
        loadTask.execute((Void) null);
    }

    private void displayProfile(){
        user = uvm.getUser();
        if (StringUtil.notNullOrEmpty(user.getSnailview())) {
            Picasso.with(getContext())
                    .load(user.getSnailview())
                    .into(user_avatar);
        }

        if (!user.getCustomer_service().equals("")) {
            customServiceBtn.setText("客户服务：" + user.getCustomer_service() + "");
        }

        performanceTxt.setText( user.getPerformance());

        if (!WoyaoooApplication.hasLogin){
            username.setText("");
            userLocation.setText("");
            userTitle.setText("点此注册/登录");
            userVerify.setText("");
            performanceTxt.setText("");

        }else {
            userVerify.setText(user.getVerify());
            if (user.getDisplayname().equals("")) {
                username.setText("匿名");
            } else {
                username.setText(user.getDisplayname());
            }
            if (user.getLocation().equals("")) {
                userLocation.setText("[所在地不明]");
            } else {
                userLocation.setText(user.getLocation());
            }

            if (user.getTitle().equals("")) {
                userTitle.setText("[无组织身份]");
            } else {
                userTitle.setText(user.getTitle());
            }
        }

        updates_num.setText( user.getMoves_num() +"");
        followers_num.setText(user.getApplyme() +"");
        marked_num.setText( user.getIapply() +"");
        history_num.setText(user.getHistory_num() +"");
    }


    public   void cancelUser(){
        AsyncTask<Void, Void, BaseResponse> task = new AsyncTask<Void, Void, BaseResponse>() {
            @Override
            protected BaseResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<BaseResponse> responseCall = svc.setProfileAttr(WoyaoooApplication.userId,"canceldate","");
                BaseResponse ret = null ;
                try {
                    ret = responseCall.execute().body();
                } catch (IOException e) {
                    e.printStackTrace();
                    ret = null;
                }
                return ret;
            }

            @Override
            protected void onPostExecute(final BaseResponse response) {
                if (response != null) {

                    if (response.isSuccess()){

                        Dialog alertDialog = new AlertDialog.Builder(getContext()).
                                setTitle("信息").
                                setMessage(response.getMessage()).
                                setIcon(R.drawable.ic_launcher).
                                setPositiveButton("确定", new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        userId = null;
                                        SharedPreferences preferences =  getContext().getSharedPreferences("login", 0);
                                        SharedPreferences.Editor editor = preferences.edit();
                                        editor.clear();
                                        editor.commit();
                                        getActivity().finish();
//                                        Intent intent = new Intent(getContext(), LoginActivity.class);
//                                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                                        startActivity(intent);
                                    }
                                }).

                                create();
                        alertDialog.show();

                    }else{
                       Common.alert(getContext(),response.getMessage());
                    }
                } else {
                    Common.alert(getContext(),"系统发生错误");
                }
            }

            @Override
            protected void onCancelled() {
            }
        };
        task.execute((Void) null);

    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if  (requestCode == MYREGISTER_CODE && resultCode == 666 ){
            loadProfile();


        }

        if  (requestCode == MYACCOUNT_CODE  ){
            loadProfile();
        }

        if  (requestCode == ADD_DEMAND_CODE && resultCode == 666  ){
            loadProfile();
        }

        if  (requestCode == ADD_UPDATE_CODE && resultCode == 666  ){
            loadProfile();
        }

    }
}
